package org.ran.demo.http.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

public class StreamUtil {
    private StreamUtil() {}
    public static String readLine(InputStream in) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b;
        while (( b = in.read())>-1) {
            if (b=='\r') {
                b = in.read();
                if (b=='\n') {
                    return new String(bos.toByteArray(),StandardCharsets.ISO_8859_1);
                }else {
                    bos.write('\r');
                    bos.write(b);
                }
            }
            bos.write(b);
        }
        return new String(bos.toByteArray(),StandardCharsets.ISO_8859_1);
    }
    
    public static byte[] readLength(InputStream in,int length) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b;
        int counter=0;
        while (( b = in.read())>-1&&counter<length) {
            bos.write(b);
            counter++;
        }
        return bos.toByteArray();
    }
    private static final byte[] LINE_END= {(byte)'\r',(byte)'\n'};
    public static void writeLine(String text, OutputStream out) throws Exception {
        out.write(text.getBytes(StandardCharsets.ISO_8859_1));
        out.write(LINE_END);
    }
}
